﻿using MediatR;
using RBAC_Uthorization.Domain;
using RBAC_Uthorization.Domain.Entity;
using RBAC_Uthorization.Infrstructre.Interface;
using RBAC_Uthorization.Read.API.Application.Command.RoleCommand;
using RBAC_Uthorization.Read.API.DTO;
using RBAC_Uthorization.Read.API.DTO.Response.Role;

namespace RBAC_Uthorization.Read.API.Application.CommandHandlers.RoleHandler
{
    public class RoleSelectCommandHandlers : IRequestHandler<RoleSelectCommand, ApiResult<List<RoleSelectDto>>>
    {
        private readonly IRoleRepository _roleRepository;
        private readonly ILogger<RoleSelectCommandHandlers> _logger;

        public RoleSelectCommandHandlers(ILogger<RoleSelectCommandHandlers> logger, IRoleRepository roleRepository)
        {
            _logger = logger;
            _roleRepository = roleRepository;
        }

        public async Task<ApiResult<List<RoleSelectDto>>> Handle(RoleSelectCommand request, CancellationToken cancellationToken)
        {
            try
            {
                List<sys_role> role;
                if (request.offlc_id == "10086")
                {
                    role = await _roleRepository.GetAllAsync();
                }
                else
                {
                    role = await _roleRepository.GetAllAsunc(x => x.offic_id == request.offlc_id && x.del_flag == 0&&x.sys_id==request.sys_id);
                }
                if (role == null)
                {
                    return new ApiResult<List<RoleSelectDto>> { Code = ResultCode.NoContent, Message = "角色不存在" };
                }
                var roleSelectDto = role.Select(x => new RoleSelectDto
                {
                    id = x.id,
                    name = x.name,
                }).ToList();
                return new ApiResult<List<RoleSelectDto>> { Data = roleSelectDto };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取角色信息失败");
                return new ApiResult<List<RoleSelectDto>> { Code = ResultCode.Fail, Message = "获取角色信息失败" };
            }
        }
    }
}
